package com.ygxsk.carhome.ui.insurance;

import android.Manifest;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.flyco.roundview.RoundTextView;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;
import com.hjq.toast.Toaster;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.trello.rxlifecycle4.android.ActivityEvent;
import com.ygxsk.carhome.R;
import com.ygxsk.carhome.alertview.AlertView;
import com.ygxsk.carhome.alertview.OnItemClickListener;
import com.ygxsk.carhome.constant.ConstantApi;
import com.ygxsk.carhome.constant.ConstantSign;
import com.ygxsk.carhome.constant.ExtraKey;
import com.ygxsk.carhome.constant.ExtraValue;
import com.ygxsk.carhome.enumwrap.CallHistoryBusinessType;
import com.ygxsk.carhome.enumwrap.CarRenewalStatus;
import com.ygxsk.carhome.event.EventCarRenewalDetail;
import com.ygxsk.carhome.event.EventCarRenewalMain;
import com.ygxsk.carhome.listener.AuthorityCallbackListener;
import com.ygxsk.carhome.listener.Delivery;
import com.ygxsk.carhome.listener.ErrorParentExtraSingle;
import com.ygxsk.carhome.response.CarRenewalBean;
import com.ygxsk.carhome.response.CarRenewalDetailBean;
import com.ygxsk.carhome.retrofit.AddLogUpLoadInfo;
import com.ygxsk.carhome.retrofit.ApiException;
import com.ygxsk.carhome.retrofit.ApiRequestSubListener;
import com.ygxsk.carhome.retrofit.ApiService;
import com.ygxsk.carhome.retrofit.ErrorConsumer;
import com.ygxsk.carhome.retrofit.NetworkManager;
import com.ygxsk.carhome.retrofit.ResponseTransformer;
import com.ygxsk.carhome.sys.PermissionInterceptor;
import com.ygxsk.carhome.sys.PermissionNameConvert;
import com.ygxsk.carhome.ui.ErrorActivity;
import com.ygxsk.carhome.utils.CommTools;
import com.ygxsk.carhome.utils.CommUtils;
import com.ygxsk.carhome.utils.StringCodeUtils;
import com.ygxsk.integrated.retrofit.Parameterkey;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import cn.bingoogolapple.photopicker.widget.BGANinePhotoLayout;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

/*
 * @Author:itchenqi175@163.com
 * @Time:2023-09-19  15:41
 * @Description:一键续保 的详情页面；
 */
public class CarRenewalDetailActivity extends ErrorActivity implements ErrorParentExtraSingle, EasyPermissions.PermissionCallbacks {

    @BindView(R.id.refreshLayoutInRenewalDetail)
    SmartRefreshLayout refreshLayoutInRenewalDetail;

    //联系人姓名
    @BindView(R.id.textViewPersonValueDetail)
    TextView textViewPersonValueDetail;

    //该单据的状态
    @BindView(R.id.textViewPersonOrderStateDetail)
    TextView textViewPersonOrderStateDetail;

    //手机号信息
    @BindView(R.id.textViewPersonPhoneValueDetail)
    TextView textViewPersonPhoneValueDetail;

    //车牌号
    @BindView(R.id.textViewCarNumberValueDetail)
    TextView textViewCarNumberValueDetail;

    //身份证号
    @BindView(R.id.textViewIdCardNumberValueDetail)
    TextView textViewIdCardNumberValueDetail;

    //添加 一个时间提交
    @BindView(R.id.textViewCreateTimeRenewalDetail)
    TextView textViewCreateTimeRenewalDetail;

    //车辆 行车本信息
    @BindView(R.id.linearLayoutOutSideDrivingBookDetail)
    LinearLayout linearLayoutOutSideDrivingBookDetail;

    //行车本的九宫格
    @BindView(R.id.npl_item_moment_photos_renewal_detail)
    BGANinePhotoLayout npl_item_moment_photos_renewal_detail;

    //外侧的两个按钮的包裹
    @BindView(R.id.relativeLayoutTwoButtonDetail)
    RelativeLayout relativeLayoutTwoButtonDetail;

    @BindView(R.id.roundTextViewViewTakeOrderDetail)
    RoundTextView roundTextViewViewTakeOrderDetail;

    @BindView(R.id.roundTextViewViewCompleteOrderDetail)
    RoundTextView roundTextViewViewCompleteOrderDetail;

    //携带这个实体的内容过来
    private CarRenewalBean extra_car_renewal_list_item_bean;

    //是取值的 这个一键续保的id内容
    private String extra_car_renewalInsuranceId;

    //该页面仅仅只有预览的能力
    private static final int PRC_PHOTO_PREVIEW = 1;

    private BGANinePhotoLayout mCurrentClickNpl;

    private BGANinePhotoLayout.Delegate bgaNinePhotoLayoutDelegate = new BGANinePhotoLayout.Delegate() {
        @Override
        public void onClickNinePhotoItem(BGANinePhotoLayout ninePhotoLayout, View view, int position, String model, List<String> models) {
            //点击九宫格,查看大图
            mCurrentClickNpl = ninePhotoLayout;

            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {

                photoPreviewWrapper();

            } else {

                photoPreviewIntentXXPermissions();

            }

        }

        @Override
        public void onClickExpand(BGANinePhotoLayout ninePhotoLayout, View view, int position, String model, List<String> models) {
            //点击展开的
            ninePhotoLayout.setIsExpand(true);
            ninePhotoLayout.flushItems();
        }
    };

    /**
     * 图片预览，兼容6.0动态权限
     */
    @AfterPermissionGranted(PRC_PHOTO_PREVIEW)
    private void photoPreviewWrapper() {
        if (mCurrentClickNpl == null) {
            return;
        }

        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};

        if (EasyPermissions.hasPermissions(CarRenewalDetailActivity.this, perms)) {

            CommTools.photoPreviewIntent(mActivityInstance, mActivityInstance, mCurrentClickNpl);

        } else {
            //EasyPermissions.requestPermissions(this, "图片预览需要以下权限:\n\n1.访问设备上的照片", PRC_PHOTO_PREVIEW, perms);
            EasyPermissions.requestPermissions(this, StringUtils.getString(R.string.imagenicelook), PRC_PHOTO_PREVIEW, perms);
        }
    }

    private void photoPreviewIntentXXPermissions() {

        if (!XXPermissions.isGranted(CarRenewalDetailActivity.this, com.hjq.permissions.Permission.READ_MEDIA_IMAGES)) {

            CommUtils.checkMaterialDialog(materialDialog);

            materialDialog = CommUtils.authorityRequest(mActivityInstance, ConstantSign.MATERIALDIALOG_AUTHORITY_CONTENT_ALBUM, new AuthorityCallbackListener() {
                @Override
                public void doSomeThing() {

                    CommUtils.checkMaterialDialog(materialDialog);

                    XXPermissions.with(CarRenewalDetailActivity.this)
                            // 适配分区存储应该这样写
                            //.permission(Permission.Group.STORAGE)
                            // 不适配分区存储应该这样写
//                    .permission(com.hjq.permissions.Permission.CAMERA)//
                            .permission(com.hjq.permissions.Permission.READ_MEDIA_IMAGES)//
//                  .permission(com.hjq.permissions.Permission.READ_MEDIA_VIDEO)//
//                  .permission(com.hjq.permissions.Permission.READ_MEDIA_AUDIO)//
                            //).permission(com.hjq.permissions.Permission.MANAGE_EXTERNAL_STORAGE
                            .interceptor(new PermissionInterceptor())
                            .request(new OnPermissionCallback() {

                                @Override
                                public void onGranted(@NonNull List<String> permissions, boolean allGranted) {

                                    if (!allGranted) {
                                        return;
                                    }

                                    Toaster.show(String.format(getString(R.string.demo_obtain_permission_success_hint),
                                            PermissionNameConvert.getPermissionString(CarRenewalDetailActivity.this, permissions)));

                                    CommTools.photoPreviewIntent(mActivityInstance, mActivityInstance, mCurrentClickNpl);

                                }
                            });
                }
            });

        } else {

            CommTools.photoPreviewIntent(mActivityInstance, mActivityInstance, mCurrentClickNpl);

        }

    }

//    private void photoPreviewIntent() {
//
////        File downloadDir = new File(Environment.getExternalStorageDirectory(), ConstantSign.BGAPHOTOPICKERDOWNLOAD);
//        File downloadDir = new File(PathUtils.getExternalAppFilesPath(), ConstantSign.BGAPHOTOPICKERDOWNLOAD);
//        BGAPhotoPreviewActivity.IntentBuilder photoPreviewIntentBuilder = new BGAPhotoPreviewActivity.IntentBuilder(CarRenewalDetailActivity.this);
//
//        if (true) {
//            // 保存图片的目录，如果传 null，则没有保存图片功能
//            photoPreviewIntentBuilder.saveImgDir(downloadDir);
//        }
//
//        if (mCurrentClickNpl.getItemCount() == 1) {
//            // 预览单张图片
//            photoPreviewIntentBuilder.previewPhoto(mCurrentClickNpl.getCurrentClickItem());
//
//        } else if (mCurrentClickNpl.getItemCount() > 1) {
//            // 预览多张图片
//            photoPreviewIntentBuilder.previewPhotos(mCurrentClickNpl.getData())
//                    .currentPosition(mCurrentClickNpl.getCurrentClickItemPosition()); // 当前预览图片的索引
//        }
//
//        startActivity(photoPreviewIntentBuilder.build());
//
//    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (requestCode == PRC_PHOTO_PREVIEW) {
            //Toast.makeText(this, StringUtils.getString(R.string.image_preview), Toast.LENGTH_SHORT).show();
            ToastUtils.showShort(StringUtils.getString(R.string.image_preview));
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mActivityInstance = this;

        processExtraData();

        initloading();

        initViews();

        gainDatas();

        //这里有页面刷新，或者编辑完毕，通知页面刷新的逻辑；
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_car_renewal_detail;
    }

    @Override
    protected void initToolBar(ToolbarHelper toolbarHelper) {

//        toolbarHelper.setLayoutSao(false, null);
        toolbarHelper.setTitle(getString(R.string.title_detail_renewal));
        toolbarHelper.setVersionName(true, AppUtils.getAppVersionName());
        toolbarHelper.setLayoutLeft(true, R.drawable.backicon, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //checkEdit();
                methodBack();
            }
        });

        toolbarHelper.setLayoutClose(false, "", null);

        //右侧是【编辑】
        toolbarHelper.setLayoutRight(false, 0, "", null);

//        toolbarHelper.setLayoutRight(false, 0, getString(R.string.button_edit_right), new ClickUtils.OnDebouncingClickListener() {
//            @Override
//            public void onDebouncingClick(View v) {
//
//                //携带信息跳转到【编辑-提交】页面；
//                Bundle extra_bundle = new Bundle();
//
//                //携带 订单的id，获取一次详情，再修改
//
//                ActivityUtils.startActivity(extra_bundle, LeadAddSubmitActivity.class);
//
//            }
//        });

    }

    @Override
    protected void onClickNodata(View v) {

        gainDatas();

    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();

        ImmersionBar.with(this)//
                .titleBar(R.id.toolbarygxskout)
                .fitsSystemWindows(true)//解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                //.statusBarColor(R.color.colorPrimary)//
                //.navigationBarColor(R.color.colorPrimary)//
                //.keyboardEnable(true)
                .init();

    }

    @Override
    protected void initViews() {

        //拨打电话信息

        //
        refreshLayoutInRenewalDetail.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {

                refreshLayout.getLayout().post(new Runnable() {
                    @Override
                    public void run() {

                        gainDatas();

                        refreshLayout.finishRefresh();

                    }
                });

            }
        });

        //接单 按钮逻辑
        if (roundTextViewViewTakeOrderDetail != null) {

            roundTextViewViewTakeOrderDetail.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    CommUtils.checkDialog(mAlertView);
                    mAlertView = new AlertView(StringUtils.getString(R.string.clearaddorsubmitsuretitletips), //提示
                            StringUtils.getString(R.string.submit_carrenewal_takeorder_message),//提示内容 确定接单
                            StringUtils.getString(R.string.clearcachecancel), //取消
                            new String[]{StringUtils.getString(R.string.clearaddorsubmitsure)},//确定
                            null, mActivityInstance, AlertView.Style.Alert, new OnItemClickListener() {//
                        @Override
                        public void onItemClick(Object o, int position) {

                            if (position != AlertView.CANCELPOSITION) {

                                method_gainTakeOrderSubmitInfo_upLoad(extra_car_renewalInsuranceId);

                            }

                        }
                    });

                    mAlertView.setCancelable(true);
                    mAlertView.show();

                }
            });

        }


        //完成 按钮 逻辑

        if (roundTextViewViewCompleteOrderDetail != null) {

            roundTextViewViewCompleteOrderDetail.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    CommUtils.checkDialog(mAlertView);
                    mAlertView = new AlertView(StringUtils.getString(R.string.clearaddorsubmitsuretitletips), //提示
                            StringUtils.getString(R.string.submit_carrenewal_completeorder_message),//提示内容 确定审核通过
                            StringUtils.getString(R.string.clearcachecancel), //取消
                            new String[]{StringUtils.getString(R.string.clearaddorsubmitsure)},//确定
                            null, mActivityInstance, AlertView.Style.Alert, new OnItemClickListener() {//
                        @Override
                        public void onItemClick(Object o, int position) {

                            if (position != AlertView.CANCELPOSITION) {

                                method_gainCompleteSubmitInfo_upLoad(extra_car_renewalInsuranceId);

                            }

                        }
                    });

                    mAlertView.setCancelable(true);
                    mAlertView.show();

                }
            });
        }


    }

    @Override
    protected void gainDatas() {

        if (NetworkUtils.isConnected()) {

            gainDatasFromServer();

        } else {
            //遮盖信息
            netWorkError();
        }


    }

    //完成 按钮
    private void method_gainCompleteSubmitInfo_upLoad(String _ids) {

        //第一种方式
        //Integer[] idsArray = new Integer[]{Integer.parseInt(_ids)};
        //第二种方式
        String[] idsArray = new String[]{_ids};

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.ids, idsArray);

//        map.put(Parameterkey.status, ConsignStatus.STATUS_HAS_VERIFY.getIndex());//2:已审核 即审核通过状态

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_COMPLETERENEWALINSURANCE_URL);//
        addLogUpLoadInfo.setUrlPath(ApiService.completeRenewalInsurance_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .completeRenewalInsurance(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
//                .compose(CarRenewalFragment.this.bindUntilEvent(ActivityEvent.DESTROY))
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<String>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);
                    }
                })).subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String stringValue) throws Throwable {

                        //TipDialog.show(StringUtils.getString(R.string.add_submit_success), WaitDialog.TYPE.SUCCESS);
                        EventCarRenewalMain eventCarRenewalMain = new EventCarRenewalMain();
                        eventCarRenewalMain.setMessage(ExtraValue.EVENTBUS_EVENT_TO_REFRESH_CAR_RENEWAL_MAIN_LIST);
                        EventBus.getDefault().post(eventCarRenewalMain);

                        //通知主页列表刷新
                        EventCarRenewalDetail eventCarRenewalDetail = new EventCarRenewalDetail();
                        eventCarRenewalDetail.setMessage(ExtraValue.EVENTBUS_EVENT_TO_REFRESH_CAR_RENEWAL_DETAIL);
                        EventBus.getDefault().post(eventCarRenewalDetail);

                        methodSubmitSuccess(mActivityInstance, null);

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                    }
                });
    }


    //接单 按钮
    private void method_gainTakeOrderSubmitInfo_upLoad(String _ids) {

        //传递参数的形式变成了如下格式：
//        {
//            "ids":["9"]
//        }

//        ArrayList<String> idsList = new ArrayList<>();
//        idsList.add(_ids);
        String[] idsArray = new String[]{_ids};
        //idsArray[0] = _ids;

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.ids, idsArray);//

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_RECEIVERENEWALINSURANCE);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.receiveRenewalInsurance_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(false);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .receiveRenewalInsurance(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
//                .compose(CarRenewalFragment.this.bindUntilEvent(ActivityEvent.DESTROY))
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<String>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);

                        if (!TextUtils.isEmpty(serverMessage)) {
                            ToastUtils.showShort(serverMessage);
                        }

                    }
                })).subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String stringValue) throws Throwable {

                        //TipDialog.show(StringUtils.getString(R.string.add_submit_success), WaitDialog.TYPE.SUCCESS);

                        //通知 列表刷新
                        EventCarRenewalMain eventCarRenewalMain = new EventCarRenewalMain();
                        eventCarRenewalMain.setMessage(ExtraValue.EVENTBUS_EVENT_TO_REFRESH_CAR_RENEWAL_MAIN_LIST);
                        EventBus.getDefault().post(eventCarRenewalMain);

                        //通知该详情页 的刷新
                        EventCarRenewalDetail eventCarRenewalDetail = new EventCarRenewalDetail();
                        eventCarRenewalDetail.setMessage(ExtraValue.EVENTBUS_EVENT_TO_REFRESH_CAR_RENEWAL_DETAIL);
                        EventBus.getDefault().post(eventCarRenewalDetail);


                        methodSubmitSuccess(mActivityInstance, null);

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                        //
                    }
                });
    }


    private void gainDatasFromServer() {

//        latentCustomerId_upLoad = extra_lead_list_item_bean.getLatentCustomerId();

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.id, extra_car_renewalInsuranceId);

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_GETBYID_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.getById_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_GET);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                //.getById(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue), MediaType.parse(ApiService.HEADER_JSON)))
                .receiveRenewalInsurance_getById(extra_car_renewalInsuranceId)
                .compose(CarRenewalDetailActivity.this.bindUntilEvent(ActivityEvent.DESTROY))
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<CarRenewalDetailBean>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);

                        if (TextUtils.isEmpty(serverMessage)) {
                            ToastUtils.showShort(serverMessage);
                        }

                    }
                })).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Throwable {
                        loadingGone();
                        //
                    }
                }).subscribe(new Consumer<CarRenewalDetailBean>() {
                    @Override
                    public void accept(CarRenewalDetailBean carRenewalDetailBean) throws Throwable {

                        //主要是顶部变动
                        if (carRenewalDetailBean != null) {

                            //填充id 或者 重新赋值 id
                            extra_car_renewalInsuranceId = carRenewalDetailBean.getRenewalInsuranceId();

                            //头部信息挨个填充
                            Delivery.getInstance().post(new Runnable() {
                                @Override
                                public void run() {

                                    //联系人姓名 填充
                                    CommUtils.setText(textViewPersonValueDetail, carRenewalDetailBean.getName());

                                    //该单据的状态文本
                                    CommUtils.setText(textViewPersonOrderStateDetail, carRenewalDetailBean.getStatusString());

                                    //填充 手机号信息
//                                    CommUtils.setText(textViewPersonPhoneValueDetail, carRenewalDetailBean.getPhone());
                                    CommUtils.setText(textViewPersonPhoneValueDetail, StringCodeUtils.mobileEncrypt(carRenewalDetailBean.getPhone()));

                                    textViewPersonPhoneValueDetail.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            clickButton_toCallPhone(CarRenewalDetailActivity.this, carRenewalDetailBean.getPhone(), CallHistoryBusinessType.BUSINESSTYPE_10.getIndex());
                                        }
                                    });

                                    //填充 车牌号
                                    CommUtils.setText(textViewCarNumberValueDetail, carRenewalDetailBean.getLicenseNo());

                                    //填充 身份证信息
                                    CommUtils.setText(textViewIdCardNumberValueDetail, carRenewalDetailBean.getIdCard());

                                    //填充 时间信息
                                    CommUtils.setText(textViewCreateTimeRenewalDetail, carRenewalDetailBean.getCreateTime());

                                    String drivingNotebook = carRenewalDetailBean.getDrivingNotebook();

                                    String resultImage = carRenewalDetailBean.getUrlPrefix() + drivingNotebook;

                                    //行车本信息
                                    ArrayList<String> drivingNotebookList = new ArrayList<>();
                                    drivingNotebookList.add(resultImage);

                                    if (!TextUtils.isEmpty(drivingNotebook)) {

                                        if (!drivingNotebook.endsWith(Parameterkey.null_value)) {

                                            //设置外侧布局展示|：
                                            CommUtils.setViewVisible(linearLayoutOutSideDrivingBookDetail);

                                            //九宫格：
                                            if (npl_item_moment_photos_renewal_detail != null) {
                                                npl_item_moment_photos_renewal_detail.setData(drivingNotebookList);
                                                npl_item_moment_photos_renewal_detail.setDelegate(bgaNinePhotoLayoutDelegate);
                                            }

                                        } else {
                                            CommUtils.setViewGone(linearLayoutOutSideDrivingBookDetail);
                                        }

                                    } else {
                                        //设置外侧布局展示|：
                                        CommUtils.setViewGone(linearLayoutOutSideDrivingBookDetail);
                                    }


                                    //状态的 数值格式
                                    String status = carRenewalDetailBean.getStatus();

                                    //            status  0未接单  1已接单   2已完成
//               public enum CarRenewalStatus {
//                    status  0未接单  1已接单   2已完成
//                    STATUS_NOT_TAKEORDER("0", "未接单"),
//                    STATUS_HAS_TAKEORDER("1", "已接单"),
//                    STATUS_HAS_COMPLETE("2", "已完成");

                                    if (TextUtils.equals(status, CarRenewalStatus.STATUS_NOT_TAKEORDER.getIndex())) {

                                        CommUtils.setViewVisible(relativeLayoutTwoButtonDetail);

                                        //接单 按钮 展示
                                        CommUtils.setViewVisible(roundTextViewViewTakeOrderDetail);
                                        //完成 按钮  隐藏
                                        CommUtils.setViewGone(roundTextViewViewCompleteOrderDetail);


                                    } else if (TextUtils.equals(status, CarRenewalStatus.STATUS_HAS_TAKEORDER.getIndex())) {

                                        CommUtils.setViewVisible(relativeLayoutTwoButtonDetail);

                                        //接单 按钮 展示
                                        CommUtils.setViewGone(roundTextViewViewTakeOrderDetail);
                                        //完成 按钮  隐藏
                                        CommUtils.setViewVisible(roundTextViewViewCompleteOrderDetail);

                                    } else if (TextUtils.equals(status, CarRenewalStatus.STATUS_HAS_COMPLETE.getIndex())) {

                                        CommUtils.setViewGone(relativeLayoutTwoButtonDetail);

                                    }

                                }
                            });

                        }
                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                        //

                    }
                });

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThreadInCarRenevalDetail(EventCarRenewalDetail eventCarRenewalDetail) {

        if (eventCarRenewalDetail != null) {

            if (eventCarRenewalDetail.getMessage() == ExtraValue.EVENTBUS_EVENT_TO_REFRESH_CAR_RENEWAL_DETAIL) {

//                pagination_upLoad = Parameterkey.pageNum_default_first;
//
//                if (mDataResources != null && !mDataResources.isEmpty()) {
//                    mDataResources.clear();
//                }
//
//                if (consignMainAdapter != null) {
//                    consignMainAdapter.notifyDataSetChanged();
//                }

                gainDatasFromServer();

            }

        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        EventBus.getDefault().unregister(this);

    }

    @Override
    protected void methodBack() {
        methodBackFinish();
    }

    @Override
    public void processExtraData() {

        //use the data received here
        Bundle bundle = this.getIntent().getExtras();

        if (bundle != null) {

//            LogUtils.d(ConstantSign.LOGCAT_NOMAL + extra_jumpfrom_where);

            extra_car_renewal_list_item_bean = bundle.getParcelable(ExtraKey.EXTRA_CAR_RENEWAL_LIST_ITEM_BEAN);

            if (extra_car_renewal_list_item_bean != null) {

                extra_car_renewalInsuranceId = extra_car_renewal_list_item_bean.getRenewalInsuranceId();

            }

        }

    }
}